<template>
  <el-container style="height: 600px; border: 1px solid #eee">
    <!-- 编辑资源的弹出框 -->
    <el-dialog title="修改商品规格" :visible.sync="updateFormVisible">
      <el-form ref="updateForm" :model="updateForm" :rules="rules">
        <el-form-item
          :label="tableFomat[0].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
        >
          <el-input v-model="updateForm.goods_no" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item
          :label="tableFomat[1].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
        >
          <el-input v-model="updateForm.goods_name" autocomplete="off" disabled />
        </el-form-item>
        <el-form-item
          :label="tableFomat[2].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
        >
          <el-input v-model="updateForm.goods_brief" autocomplete="off" disabled />
        </el-form-item>
        <br>
        <el-button icon="el-icon-plus" type="primary" size="mini" plain circle @click="addItem" />
        <div v-for="(item, index) in updateForm.specification" :key="index">
          <el-form-item
            label="规格"
            :label-width="formLabelWidth"
            required
            style="display:inline-block"
          >
            <el-tag type="info" size="mini">规格名称</el-tag>
            <el-button
              v-show="index == 0 ? false : true"
              icon="el-icon-minus"
              type="danger"
              size="mini"
              plain
              circle
              @click="deleteItem(item, index)"
            />
            <el-form-item
              :prop="'specification.' + index + '.name'"
              :rules="[
                { required: true, message: '请输入商品规格名称', trigger: 'blur' },
                { max: 10, message: '长度在不能大于 10 个字符', trigger: 'blur' }
              ]"
            >
              <el-input v-model="item.name" autocomplete="off" />
            </el-form-item>
            <div
              v-for="(item1, index1) in updateForm.specification[index].properties"
              :key="index1"
            >
              <el-tag type="info" size="mini">规格属性值</el-tag>
              <el-form-item
                :prop="'specification.'+index+'.properties.' + index1 + '.value'"
                :rules="[{ required: true, message: '请输入商品规格属性值', trigger: 'blur' },{ max: 30, message: '长度在不能大于 30 个字符', trigger: 'blur' }]"
              >
                <el-input v-model="item1.value" />
              </el-form-item>
              <i
                class="el-icon-circle-plus-outline"
                style="font-size:20px"
                @click="addItem1(index)"
              />
              <i
                v-show="index1 == 0 ? false : true"
                class="el-icon-remove-outline"
                style="font-size:20px"
                @click="deleteItem1(item1, index, index1)"
              />
            </div>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateGoods('updateForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-container>
      <!-- 搜索区 -->
      <el-header>
        <el-input v-model="search.code" placeholder="商品编号" style="width:300px;" />
        <el-input v-model="search.name" placeholder="商品名称" style="width:300px;" />
        <el-button type="primary" icon="el-icon-search" @click="searchGoods()">搜索</el-button>
      </el-header>

      <!-- 功能区 -->
      <el-main style="height:600px;">
        <el-row>
          <el-button type="primary" size="mini" @click="Edit()">编辑</el-button>
        </el-row>
        <!-- 表格 组件 -->
        <datatable
          :table-fomat="tableFomat"
          :table-data="tableData"
          :total="tableData.length"
          :delete-visible="false"
          @handleEdit="handleEdit"
          @handleSelectionChange="handleSelectionChange"
        >
          <el-table-column label="规格" width="200">
            <template slot-scope="scope">
              <el-tag
                v-for="ele in scope.row.specification"
                :key="ele.name"
                type="info"
                style="margin: 0px 2px"
              >{{ ele.name }}</el-tag>
            </template>
          </el-table-column>
        </datatable>
      </el-main>
    </el-container>
  </el-container>
</template>
<style>
/* 容器头部 和  */
.el-header {
  line-height: 60px;
}
.el-aside {
  width: 200px !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  color: #333;
  background-color: white;
}
</style>
<script>
import datatable from '@/views/my-views/components/table'
import goods from '@/sql/table-field/index'
import { tsFormatTime } from '@/tools/util'
import { mapGetters } from 'vuex'
import FlakeId from 'flake-idgen'
import informat from 'biguint-format'
// 使用雪花算法生成商品的编号
var flakeIdGen = new FlakeId()
export default {
  name: 'GoodsProperty',
  components: {
    datatable
  },
  data() {
    return {
      // 表单认证规则
      rules: {
        specification_name: [
          { required: true, message: '请输入商品规格名称', trigger: 'blur' },
          { max: 10, message: '长度在不能大于 10 个字符', trigger: 'blur' }
        ],
        specification_name_value: [
          { required: true, message: '请输入商品规格属性值', trigger: 'blur' },
          { max: 20, message: '长度在不能大于 20 个字符', trigger: 'blur' }
        ]
      },
      // 文件上传是放大图片
      dialogImageUrl: '',
      dialogVisible: false,
      // 解决notice通知栏覆盖问题
      notifyPromise: Promise.resolve(),
      // 搜索输入框的值
      search: {
        code: '',
        name: ''
      },
      // 表格显示格式(列名以及列对应显示的数据)
      tableFomat: goods.goodsProperty,
      // 表格数据
      tableData: [],
      // 当前表格选中的数据
      multipleSelection: [],

      formLabelWidth: '120px',

      // 修改的弹出框设置
      updateFormVisible: false,
      updateForm: {
        _id: '',
        // 商品编号
        goods_no: '',
        // 商品的名字
        goods_name: '',
        // 商品的简短描述
        goods_brief: '',
        // 商品规格
        specification: [
          {
            id: '',
            name: '',
            properties: [
              {
                value: ''
              }
            ]
          }
        ]
      }
    }
  },
  computed: {
    // 从store中的getters中获取数据(store/getters.js)
    ...mapGetters(['goodsList'])
  },
  mounted() {
    // 如果state中有数据则从state中读取
    if (this.goodsList.length !== 0) {
      // 使用缓存
      this.tableData = this.goodsList
    } else {
      // 获取商品列表
      this.getGoodsList()
    }
  },
  methods: {
    addItem() {
      this.updateForm.specification.push({
        id: informat(flakeIdGen.next(), 'dec'),
        name: '',
        properties: [
          {
            value: ''
          }
        ]
      })
    },
    deleteItem(item, index) {
      this.updateForm.specification.splice(index, 1)
    },
    addItem1(index) {
      this.updateForm.specification[index].properties.push({
        value: ''
      })
    },
    deleteItem1(item, index, index1) {
      this.updateForm.specification[index].properties.splice(index1, 1)
    },
    // tip提示方法
    tipformat(res, type, type_name) {
      if (res.errcode !== 0) {
        this.notifyPromise = this.notifyPromise
          .then(this.$nextTick)
          .then(() => {
            this.$notify.error({
              title: `${type}商品失败`,
              message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
              duration: 0
            })
          })
      } else {
        this.notifyPromise = this.notifyPromise
          .then(this.$nextTick)
          .then(() => {
            this.$notify({
              title: `${type}商品成功`,
              message: `${type_name}--商品${type}成功`,
              type: 'success',
              duration: 6000
            })
          })
        // 重新从数据库获取数据
        this.getGoodsList()
      }
    },
    // 数据库数据转换为前端显示数据格式
    dataBaseToFormData(value) {
      value.create_time = tsFormatTime(value.create_time, 'Y-M-D h:m:s')
      value.update_time = tsFormatTime(value.update_time, 'Y-M-D h:m:s')
      return value
    },
    // 错误请求消息提示规范
    catchError(type, err) {
      this.$notify.error({
        title: `${type}商品请求失败`,
        message: err,
        duration: 0
      })
    },
    // 修改商品信息
    updateGoods(formName) {
      const type = '修改'
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.updateFormVisible = false
          this.$store
            .dispatch('updateGoodsSpecification', this.updateForm)
            .then(res => {
              this.tipformat(res, type, this.updateForm.goods_name)
            })
            .catch(err => {
              this.catchError(type, err)
            })
        } else {
          return false
        }
      })
    },
    // 获取商品列表的方法
    getGoodsList() {
      const type = '获取'
      this.$store
        .dispatch('getGoodsListLinkGoodsType')
        .then(res => {
          if (res.errcode !== 0) {
            if (res.errcode === 42001) {
              this.$notify.error({
                title: 'Access_token过期,请重新刷登录获取',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            } else {
              this.$notify.error({
                title: '获取商品列表失败',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            }
          } else {
            this.tableData = JSON.parse(res.resp_data).data.list
            this.tableData.map(res => {
              this.dataBaseToFormData(res)
            })
            this.$store.commit('setGoodsList', this.tableData)
          }
        })
        .catch(err => {
          this.catchError(type, err)
        })
    },
    searchGoods() {
      const type = '搜索'
      this.$store
        .dispatch('searchGoods', this.search)
        .then(res => {
          if (res.errcode !== 0) {
            if (res.errcode === 42001) {
              this.$notify.error({
                title: 'Access_token过期,请重新刷登录获取',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            } else {
              this.$notify.error({
                title: '获取商品列表失败',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            }
          } else {
            this.tableData = JSON.parse(res.resp_data).data.list
            this.tableData.map(res => {
              this.dataBaseToFormData(res)
            })
          }
        })
        .catch(err => {
          // 错误请求消息提示
          this.catchError(type, err)
        })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 每列的编辑
    handleEdit(index, row) {
      this.updateFormVisible = true
      this.updateForm._id = row._id
      this.updateForm.goods_no = row.goods_no
      this.updateForm.goods_name = row.goods_name
      this.updateForm.goods_brief = row.goods_brief
      // 使用深拷贝,防止互相影响
      this.updateForm.specification = JSON.parse(
        JSON.stringify(row.specification)
      )
    },
    // 头部的编辑
    Edit() {
      if (this.multipleSelection.length === 1) {
        this.updateFormVisible = true
        this.updateFormVisible = true
        this.updateForm._id = this.multipleSelection[0]._id
        this.updateForm.goods_no = this.multipleSelection[0].goods_no
        this.updateForm.goods_name = this.multipleSelection[0].goods_name
        this.updateForm.goods_brief = this.multipleSelection[0].goods_brief
        this.updateForm.specification = this.multipleSelection[0].specification
      } else {
        this.$message('你有且必须选择一条数据')
      }
    }
  }
}
</script>
